//
//  ChangePassword.m
//  Speedater
//
//  Created by Ngo Thang on 12/31/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "ChangePassword.h"
#import "Start.h"
#import "Login.h"
#import "AppDelegate.h"
#import "JSON.h"

@interface ChangePassword (Private)

- (void)cleanup;

@end

@implementation ChangePassword (Private)

- (void)cleanup
{
    self.myScrollView = nil;
    self.oldPasswordTextField = nil;
    self.passwordTextField = nil;
    self.rePasswordTextField = nil;
    self.submitButton = nil;
}

@end


@implementation ChangePassword

@synthesize myScrollView;
@synthesize oldPasswordTextField, passwordTextField, rePasswordTextField;
@synthesize submitButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //NSLog(@"CHANGEPASSWORD -> dealloc");
    [self cleanup];
    [super dealloc];
}

#pragma mark - Custom functions

- (IBAction)submitButtonClick:(id)sender
{
    NSString *postString = [NSString stringWithFormat:@"op=changePassword&username=%@&oldPassword=%@&newPassword=%@&emailSub=%@&emailBody=%@",
                            [[NSUserDefaults standardUserDefaults] stringForKey:@"username"],
                            oldPasswordTextField.text,
                            passwordTextField.text, 
                            NSLocalizedString(@"changepass_email_subject", @""), 
                            NSLocalizedString(@"changepass_email_body", @"")];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];  
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
}

- (void)goStart
{
    // goto Start form
    for (UIViewController *vc in self.navigationController.viewControllers)
        if ([vc isKindOfClass:[Start class]]){
            //NSLog(@"USERPROFILE -> popToViewController: %@", vc);
            [self.navigationController popToViewController:vc animated:YES];
            return;
        }
}

- (void)goBack
{
    // goto login form
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //NSLog(@"CHANGEPASSWORD -> viewDidLoad");
    [super viewDidLoad];
    
    // scroll view
    [self.myScrollView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    [self.myScrollView setContentSize:CGSizeMake(320, 436)];
    
    // navigation bar
    self.navigationController.navigationBar.hidden = NO;
    
    // navigation title
    self.title = @"Ihr Passwort ändern";
    
    // navigation buttons
    UIButton *logoButton = [[UIButton alloc] initWithFrame:CGRectMake(0,2,35,35)];
    [logoButton setBackgroundImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
    [logoButton addTarget:self action:@selector(goStart) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iLButton = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
    self.navigationItem.leftBarButtonItem = iLButton;
    [logoButton release];
    [iLButton release];
    
    UIButton *backButton = [UIButton buttonWithType:100];
    [backButton setTitle:@"Zurück" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iRButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];
    self.navigationItem.rightBarButtonItem = iRButton;
    [iRButton release];
    
    [self.oldPasswordTextField becomeFirstResponder];
    
    // save state
    [AppDelegate saveState:0 withViewController:self];
}

- (void)viewDidUnload
{
    //NSLog(@"CHANGEPASSWORD -> viewDidUnload");
    [self cleanup];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark NSURLConnectionDelegete

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
    
    // loading
	HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    // loading
    [HUD hide:YES];
    
    /* Error message */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
													message:NSLocalizedString(@"Unknown network error", nil)
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];	
    
    [responseData release];
    responseData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	
	NSMutableDictionary *results = [responseString JSONValue];
    [responseString release];
    
    NSString *status = [results objectForKey:@"status"];
    
    if ([status isEqualToString:@"1"])
    {
        // goto Login form
        for (UIViewController *vc in self.navigationController.viewControllers)
            if ([vc isKindOfClass:[Login class]]){
                [self.navigationController popToViewController:vc animated:YES];
            }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                        message:NSLocalizedString(@"Your password has been changed!", nil)
                                                       delegate:nil 
                                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    else 
    {
        if ([status isEqualToString:@"2"]) status = NSLocalizedString(@"Your old password not match, please check again!", nil);
        else status = NSLocalizedString(@"", nil);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                        message:status
                                                       delegate:nil 
                                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    
    [responseData release];
    responseData = nil;
    
    // loading
    [HUD hide:YES];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
    HUD = nil;
}

@end
